import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUserInfo, getUserPermission } from '@/api/user'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  // 存token
  setToken(state, token) {
    state.token = token
    setToken(token)
    // 登陆的同时存下时间戳
    localStorage.setItem('loginTime', Date.now())
  },
  // 删token
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  // 保存用户个人信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 退出时清除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async getToken(store, data) {
    const res = await login(data)
    store.commit('setToken', res.data.jwt)
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const result = await getUserPermission()
    console.log(res, result)
    store.commit('setUserInfo', { ...res.data, ...result })
  },
  // 登出
  logout(store) {
    // 清除token
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
